package nio.serverdemo02;



import nio.NioUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * NioServerDemo 非阻塞模式
 *
 * @author chenxin
 * @date 2022/05/17 17:18
 **/
public class NioServerDemo {


    // 弊端：open.accept()没有拿到连接时，会一直循环尝试获取连接 浪费cpu性能
    public static void main(String[] args) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(16);

        ServerSocketChannel open = ServerSocketChannel.open();
        // 【设置为非阻塞模式】
        open.configureBlocking(false);
        open.bind(new InetSocketAddress(8080));
        List<SocketChannel> channels = new ArrayList<>();
        while (true) {
//            System.out.println("connecting ....");

            // 非阻塞模式 线程会继续运行 如果没有连接 accept()会返回null
            SocketChannel sc = open.accept();
            if (sc != null) {
                System.out.println("connected sc:" + sc);

                // 连接也设置为非阻塞模式
                sc.configureBlocking(false);

                channels.add(sc);
            }

            for (SocketChannel channel : channels) {
//                System.out.println("before read ... "+channel);

                // 非阻塞模式下 如果没有读到数据 read返回0
                int len = channel.read(buffer);
                if (len == 0) {
                    continue;
                }

                buffer.flip();
                System.out.println("buffer:" + NioUtils.getString(buffer));
                buffer.clear();
                System.out.println("after read ..." + channel);
            }
        }

    }


}